<?php

namespace app\common\controller;
use think\Cache;
use think\Db;
use think\Request;
use app\common\controller\Utils;
use app\admin\model\User;
/**
 * 微信相关参数生成
 * Class Wechat
 * @package app\common\controller
 */
class Wechat
{
    protected $request;
    ## 初始化操作 ##
    public function __construct(Request $request=null){
        //公众号的appid
        $this->public_appid = Db::name('systemset')->where('key','public_appid')->value('val');
        //消息验证的token
        $this->token = Db::name('systemset')->where('key','token')->value('val');
        //公众号的appsecret
        $this->public_appsecret = Db::name('systemset')->where('key','public_appsecret')->value('val');
        $this->request = is_null($request) ? Request::instance() : $request;
    }

    /**
     * 微信信息解密
     * @param  string  $appid  小程序id
     * @param  string  $sessionKey 小程序密钥
     * @param  string  $encryptedData 在小程序中获取的encryptedData
     * @param  string  $iv 在小程序中获取的iv
     * @return array 解密后的数组
     */
    public function decryptData($session_key,  $encryptedData, $iv ){
        $OK = 0;
        $IllegalAesKey = -41001;
        $IllegalIv = -41002;
        $IllegalBuffer = -41003;
        $DecodeBase64Error = -41004;

        if (strlen($session_key) != 24) {
            return $IllegalAesKey;
        }
        $aesKey=base64_decode($session_key);

        if (strlen($iv) != 24) {
            return $IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return $IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return $DecodeBase64Error;
        }
        $data = json_decode($result,true);

        return $data;
    }





    ## 获取公众号access_token ##
    public function public_access_token(){
        $public_appid=  $this->public_appid;
        $public_appsecret=  $this->public_appsecret;
        if(!Cache::get('public_access_token')){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$public_appid&secret=$public_appsecret";
            $jsonurl = file_get_contents($url);
            $data = json_decode($jsonurl,true);
            $access_token = $data['access_token'];
            Cache::set('public_access_token',$access_token,7000);
        }else{
            $access_token = Cache::get('public_access_token');
        }
        return $access_token;
    }



    ##创建公众号菜单##
    public function createmenu(){
        $public_access_token = $this->public_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$public_access_token";
        $data='{  
           "button":[  
              {      
                 "type":"miniprogram",  
                 "name":"服务中心",  
                 "url":"https://www.baidu.com",
                 "appid":"wxe0e9d38e14196d51",
                 "pagepath":"pages/index/index"
              },
            ]
        }';
        $res = Utils::post_url($url,$data);
        return $res;
    }


    /**
     * 微信授权(后端授权)
     * @param $code
     */
    public function wxAuthorization(){
        $redirect_uri = Utils::get_current_url(); //获取当前的url
        $public_appid = $this->public_appid; //公众号的appid
        $public_appsecret = $this->public_appsecret; //公众号的appsecret
        $code = input('code');
        $openid = session('openid');

        if (!$code && !$openid){
            header('content-type:text/html;charset=uft-8');
            header("Location:"."https://open.weixin.qq.com/connect/oauth2/authorize?appid=$public_appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo#wechat_redirect");
            exit;
        }
        if ($code && !$openid){
            //获取access_token
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$public_appid&secret=$public_appsecret&code=$code&grant_type=authorization_code";
            $data = file_get_contents($url);
            $data = json_decode($data,true);
            $access_token = $data['access_token']; //用户的access_token
            $openid = $data['openid']; //用户的openid

            //获取用户信息
            $userinfoulr = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
            $userinfo = file_get_contents($userinfoulr);
            $userinfo = json_decode($userinfo,true);

            //删除微信特权
            unset($userinfo['privilege']);
            $user = new User();
            //判断是否存在用户
            $userfind =$user->where('openid',$openid)->find();
            if (!$userfind){
                $user->save($userinfo);
                $uid = $user->id; //获取插入后的id
                file_put_contents('uid.txt',json_encode($uid));
            }else{
                $uid = $user->where('openid',$openid)->value('id');
                if ($uid) $user->save($userinfo,['id' => $uid]);
            }

            session('openid',$openid);
            session('uid',$uid);
        }

    }





    /**
     * vue微信授权(前端授权)
     */
    public function VueWxAuto($code=null){
        $appid = $this->public_appid;
        $appsecret = $this->public_appsecret;
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $data = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $data->errcode . '<hr>msg  :' . $data->errmsg;
            exit;
        }
        $data = json_decode(json_encode($data), true);//返回的json数组转换成array数组
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['access_token'] . '&openid=' . $data['openid'] . '&lang=zh_CN';
        $data = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $data->errcode . '<hr>msg  :' . $data->errmsg;
            exit;
        }
        $data = json_decode(json_encode($data), true);//返回的json数组转换成array数组
        $result = [];
        $user = new User();
        $userinfo = $user->where('openid',$data['openid'])->find();
        //删除微信特权
        unset($data['privilege']);
        unset($data['unionid']);
        if (!$userinfo){
            $res  = $user->save($data);
            if ($res){
                $uid = $user->id;
                $token = md5($data['openid'].$code.time()).time().$uid;
                Cache::set($token,$uid,10800);
                $result['token'] = $token;
                $result['userinfo'] = $data;
                return $result;
            }
            return false;
        }

        $user->save($data,['id'=>$userinfo['id']]);
        $token = md5($data['openid'].$code.time()).time().$userinfo['id'];
        Cache::set($token,$userinfo['id'],10800);
        $result['token'] = $token;
        $result['userinfo'] = $data;
        return $result;
    }
}


